package com.shfl.servermanage.logic.utils;

import com.shfl.servermanage.logic.constants.CommonConstants;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.UUID;

public class FileUtils {
    private FileUtils() {
    }

    public static String uploadFile(MultipartFile file, String path, Integer fileType) throws Exception {
        String separator = getSeparator();
        StringBuilder pathTemp = new StringBuilder();
        if (Objects.equals(fileType, 1)) {
            pathTemp.append(separator);
            pathTemp.append(CommonConstants.AttachType.EXECUTABLE_FILES.getFolder());
        }
        pathTemp.append(separator);
        pathTemp.append(getTempDirectory());
        String filePath = path + pathTemp.toString();
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        pathTemp.append(separator);
        pathTemp.append(file.getOriginalFilename());
        String lastFilePath = path + pathTemp.toString();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(lastFilePath);
            out.write(file.getBytes());
        } finally {
            if (out != null) {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pathTemp.toString();
    }


    public static String uploadFile(String path, StringBuilder sb) throws Exception {
        String separator = getSeparator();
        StringBuilder pathTemp = new StringBuilder();
        pathTemp.append(separator);
        pathTemp.append(CommonConstants.AttachType.SHELL_LOG.getFolder());
        pathTemp.append(separator);
        pathTemp.append(getTempDirectory());
        String filePath = path + pathTemp.toString();
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        pathTemp.append(separator);
        pathTemp.append("out.log");
        File file = new File(path + pathTemp.toString());
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));
            bw.write(sb.toString());
            bw.flush();
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
        return pathTemp.toString();
    }

    public static String getTempDirectory() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getSeparator() {
        return System.getProperty("file.separator");
    }


}
